package com.smedi.ismedi.personnel.core.port.adapter.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.smedi.ismedi.personnel.api.dto.response.PersonSyncFromImisResponse;
import com.smedi.ismedi.personnel.api.dto.response.SubOrganizationSyncFromImisResponse;
import com.smedi.ismedi.personnel.core.infrastructure.constant.CustomError;
import com.smedi.ismedi.personnel.core.port.adapter.service.ImisRemoteApiService;
import com.smedi.ismedi.web.starter.exception.LogicException;
import io.netty.util.internal.StringUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: xulinjun
 * @Date: 2021-6-15 15:26
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ImisRemoteApiServiceImpl implements ImisRemoteApiService {
    @Value("${imis.api.token-url}")
    private String tokenUrl;

    @Value("${imis.api.personInfo-url}")
    private String personInfoUrl;

    @Value("${imis.api.subOrganization-url}")
    private String subOrganizationUrl;

    @Value("${imis.api.profileImage-url}")
    private String profileImageUrl;

    @Value("${imis.api.userName}")
    private String userName;

    @Value("${imis.api.passWord}")
    private String passWord;

    // 调用接口
    private final RestTemplate restTemplate;

    @Override
    public String callToken() {
        HttpHeaders httpHeaders = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
        httpHeaders.setContentType(type);
        HashMap<String, Object> map = new HashMap<>();
        map.put("userName", userName);
        map.put("userPassword", passWord);
        HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(map, httpHeaders);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(tokenUrl, httpEntity, String.class);
        JSONObject json = JSON.parseObject(responseEntity.getBody());
        if (json.getBoolean("success")) {
            String token = json.getJSONObject("data").getString("token");
            log.info("get imis token >>> {}", token);
            return token;
        } else {
            String errorMessage = json.getString("errorMsg");
            log.error("imis-token error >>> {}", errorMessage);
            throw LogicException.raise(CustomError.CALL_REMOTE_API_ERROR);
        }
    }

    @Override
    public List<PersonSyncFromImisResponse> callPersonSync(String token) {
        if (StringUtil.isNullOrEmpty(token)) {
            throw LogicException.raise(CustomError.CALL_REMOTE_API_TOKEN_MISS);
        } else {
            HttpHeaders headers = new HttpHeaders();
            headers.add("imis-token", token);
            HttpEntity<String> httpEntity = new HttpEntity<>(null, headers);
            ResponseEntity<String> responseEntity = restTemplate.exchange(personInfoUrl, HttpMethod.GET, httpEntity, String.class);
            JSONObject json = JSON.parseObject(responseEntity.getBody());
            if (Boolean.TRUE.equals(json.getBoolean("success"))) {
                JSONArray jsonArray = json.getJSONArray("data");
                List<PersonSyncFromImisResponse> list = JSONObject.parseArray(jsonArray.toJSONString(), PersonSyncFromImisResponse.class);
                return list;
            } else {
                String errorMessage = json.getString("errorMsg");
                throw LogicException.raise(CustomError.CALL_REMOTE_API_ERROR, null, errorMessage);
            }
        }
    }

    @Override
    public List<SubOrganizationSyncFromImisResponse> callSubOrganizationSync(String token) {
        if (StringUtil.isNullOrEmpty(token)) {
            throw LogicException.raise(CustomError.CALL_REMOTE_API_TOKEN_MISS);
        } else {
            HttpHeaders headers = new HttpHeaders();
            headers.add("imis-token", token);
            HttpEntity<String> httpEntity = new HttpEntity<>(null, headers);
            ResponseEntity<String> responseEntity = restTemplate.exchange(subOrganizationUrl, HttpMethod.GET, httpEntity, String.class);
            JSONObject json = JSON.parseObject(responseEntity.getBody());
            if (json.getBoolean("success")) {
                JSONArray jsonArray = json.getJSONArray("data");
                List<SubOrganizationSyncFromImisResponse> list = JSONObject.parseArray(jsonArray.toJSONString(), SubOrganizationSyncFromImisResponse.class);
                list.stream().forEach(i -> {
                    i.setReferenceOrgId(i.getOrgId());
                });
                return list;
            } else {
                String errorMessage = json.getString("errorMsg");
                throw LogicException.raise(CustomError.CALL_REMOTE_API_ERROR, null, errorMessage);
            }
        }
    }

    @Override
    public String callImageBase64(String token, Long personId) {
        if (StringUtil.isNullOrEmpty(token)) {
            throw LogicException.raise(CustomError.CALL_REMOTE_API_TOKEN_MISS);
        } else {
            HttpHeaders headers = new HttpHeaders();
            headers.add("imis-token", token);
            HttpEntity<String> httpEntity = new HttpEntity<>(null, headers);
            // 拼接参数
            String url = UriComponentsBuilder
                    .fromHttpUrl(profileImageUrl)
                    .queryParam("personIdQuery", personId)
                    .build()
                    .encode()
                    .toString();
            // 请求
            ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
            JSONObject json = JSON.parseObject(responseEntity.getBody());
            if (json.getBoolean("success")) {
                JSONObject data = json.getJSONObject("data");
                return data.getString("base64");
            } else {
                String errorMessage = json.getString("errorMsg");
                throw LogicException.raise(CustomError.CALL_REMOTE_API_ERROR, null, errorMessage);
            }
        }
    }
}
